package com.yc.springmvc.web;

import com.google.gson.Gson;
import com.yc.springmvc.bean.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // 控制器方法=>适配器对象
        System.out.println("handler = " + handler);
        final Object loginedUser = request.getSession().getAttribute("loginedUser");
        if (loginedUser == null) {
            if( request.getRequestURI().endsWith(".do")){
                // ajax ajax请求
                // 请求转发
                final RequestDispatcher rd = request.getRequestDispatcher("/nologin.action");
                rd.forward(request,response);
//                response.setContentType("application/json;charset=utf-8");
//                Gson gson=new Gson();
//                final Result result = new Result(0, "请先登录系统", null);
//                final String j = gson.toJson(result);
//                response.getWriter().append(j);
            } else {
                // 普通请求
                // contextPath => 上下文路径 => 工程名
                final String contextPath = request.getContextPath();
                // 跳转登录页的绝对路径
                response.sendRedirect(contextPath + "/login.html");
            }
            return false;
        } else {
            return true;
        }

    }
}
